package com.example.graduation.controller.base;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.graduation.entity.pojo.Company;
import com.example.graduation.entity.pojo.Image;
import com.example.graduation.entity.pojo.User;
import com.example.graduation.service.CompanyService;
import com.example.graduation.service.ImageService;
import com.example.graduation.service.UserService;
import com.example.graduation.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

/**
 * @author Jeffery
 * <p>
 * 页面跳转的Controller
 */
@Controller
@Slf4j(topic = "BaseController")
@Api(tags = "页面跳转的controller")
public class BaseController {
    /**
     * 页面显示数据条数默认为5
     */
    private static final Integer PAGE_SIZE = 5;

    @Resource
    private UserService userService;
    @Resource
    private CompanyService companyService;
    @Resource
    private MailUtil mailUtil;
    @Resource
    private ImageService imageService;


    /**
     * 跳转首页
     *
     * @return html
     */
    @GetMapping("/")
    @ApiOperation("跳转首页")
    public String toIndex(Model model) {
        log.info("跳转首页......");
        model.addAttribute("email", ShiroUtil.getUserName());
        return "index";
    }

    /**
     * 跳转登录页面
     *
     * @return html
     */
    @GetMapping("/toLogin")
    @ApiOperation("跳转登陆页面")
    public String toLogin() {
        return "login";
    }

    /**
     * @param email      邮箱地址
     * @param password   用户密码
     * @param rememberMe 记住我
     * @return 返回用户字符串提示
     */
    @PostMapping("/login")
    @ApiOperation("登陆功能")
    @ApiImplicitParams({@ApiImplicitParam(name = "email", value = "邮箱地址", defaultValue = "1010691328@qq.com"), @ApiImplicitParam(name = "password", value = "密码", defaultValue = "111111"), @ApiImplicitParam(name = "rememberMe", value = "记住我", defaultValue = "true")})
    public String login(@RequestParam("email") String email, @RequestParam("password") String password, @RequestParam("rememberMe") String rememberMe, Model model) {
        //先查询数据库  获取对应用户的盐值加密密码
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_email", email);
        User currentUser = userService.getOne(wrapper);
        boolean isMd5Password = Md5Util.validPassword(password, currentUser.getPassword());
        boolean autoLogin = true;
        String str = "true";
        if (!str.equals(rememberMe)) {
            autoLogin = false;
        }
        if (isMd5Password) {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(email, currentUser.getPassword(), autoLogin);
            try {
                subject.login(token);
                model.addAttribute("email", email);
                return "index";
            } catch (Exception e) {
                log.error("exception : {}", e.getMessage());
                return "login";
            }
        } else {
            return "login";
        }
    }

    /**
     * 执行注销逻辑
     *
     * @return html
     */
    @GetMapping("/logout")
    @ApiOperation("注销功能")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        if (user != null) {
            log.info("注销成功！");
            subject.logout();
        }
        return "index";
    }

    /**
     * 跳转注册页面
     *
     * @return html
     */
    @GetMapping("/toRegister")
    @ApiOperation("跳转注册页面")
    public String toRegister() {
        return "register";
    }

    /**
     * 注册逻辑
     *
     * @param email    注册邮箱
     * @param password 注册密码
     * @return html
     */
    @PostMapping("/register")
    @ApiOperation("注册功能")
    @ApiImplicitParams({@ApiImplicitParam(name = "email", value = "邮箱地址", defaultValue = "1010691328@qq.com"), @ApiImplicitParam(name = "password", value = "密码", defaultValue = "111111")})
    public String register(@RequestParam("email") String email, @RequestParam("password") String password, Model model) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_email", email);
        String result = "注册失败！";

        if (userService.getOne(wrapper) != null) {
            result = "邮箱重复！";
            model.addAttribute("result", result);
            return "register";
        } else {
            User user = new User();

            user.setUsername(email);
            //盐值加密后的密码
            user.setPassword(Md5Util.getEncryptedPwd(password));
            user.setEmail(email);
            user.setGender(1);
            user.setStatus(1);
            user.setCreateTime(new Timestamp(System.currentTimeMillis()));

            try {
                userService.save(user);
                result = "注册成功";
                model.addAttribute("result", result);
                model.addAttribute("email", email);
                //发送邮件  redis缓存已经在mailUtil实现了
                mailUtil.sendMail(email);
                log.info("注册成功 : {}", user.getId());
                return "index";
            } catch (Exception e) {
                log.error("exception : {}", e.getMessage());
                model.addAttribute("result", result);
                return "register";
            }
        }
    }

    /**
     * 跳转公司页面   1
     *
     * @param pageNumber 当前页码
     * @return html
     */
    @GetMapping("/toCompany")
    @ApiOperation("跳转公司页面")
    @ApiImplicitParam(name = "pageNumber", value = "当前页数", defaultValue = "1")
    public String toCompany(@RequestParam("pageNumber") Integer pageNumber, Model model) {
        PageHelper.startPage(pageNumber, PAGE_SIZE);

        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        wrapper.eq("company_has_deleted", 0);

        //未被逻辑删除的数据
        List<Company> list = companyService.list(wrapper);
        //获取分页信息
        PageInfo<Company> pageInfo = new PageInfo<>(list);
        model.addAttribute("email", ShiroUtil.getUserId());
        model.addAttribute("pageInfo", pageInfo);
        return "companylist";
    }

    /**
     * 跳转我的简历
     *
     * @return html
     */
    @GetMapping("/user/toMyJianLi")
    @ApiOperation(" 跳转我的简历")
    public String toMyJianLi(Model model) {
        User currentUser = ShiroUtil.getCurrentUser();

        //查询我的简历
        QueryWrapper<Image> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", currentUser.getId());
        wrapper.eq("image_exc", "pdf");
        wrapper.eq("image_has_deleted", 0);
        List<Image> imageList = imageService.list(wrapper);

        model.addAttribute("currentUser", currentUser);
        model.addAttribute("email", currentUser.getEmail());
        model.addAttribute("imageList", imageList);

        return "jianli";
    }


    /**
     * 跳转上传公司界面
     *
     * @return html
     */
    @GetMapping("/company/toUploadCompany")
    @ApiOperation("跳转上传公司界面")
    public String uploadCompany(Model model) {
        User currentUser = ShiroUtil.getCurrentUser();
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("email", currentUser.getEmail());
        return "uploadCompany";
    }

    /**
     * 跳转联系我们界面
     *
     * @return html
     */
    @GetMapping("/toContactUs")
    @ApiOperation("跳转联系我们界面")
    public String toContactUs(Model model) {
        User currentUser = ShiroUtil.getCurrentUser();
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("email", currentUser.getEmail());
        return "";
    }

    /**
     * 找回密码
     *
     * @return html
     */
    @GetMapping("/toForgetPassword")
    @ApiOperation("跳转找回密码界面")
    public String forgetPassword(Model model) {
        User currentUser = ShiroUtil.getCurrentUser();
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("email", currentUser.getEmail());
        return "forgetPassword";
    }

    @GetMapping("/user/toUploadjl")
    @ApiOperation("跳转上传简历界面")
    public String toUploadjl(Model model) {
        User currentUser = ShiroUtil.getCurrentUser();
        model.addAttribute("currentUser", currentUser);
        model.addAttribute("email", currentUser.getEmail());

        return "uploadjl";
    }
}
